<template>
  <div class="sidebar">
    
    <!-- <el-card class="card-box"> -->
      <div slot="header" class="panel-header">
        <div class="header-left">
          <!-- <span class="title">水质污染模拟</span> -->
                  <div class="card-title">水质污染模拟</div>
        </div>
        <div class="header-right">
           <span class="close-btn" @click="closePanel">×</span>
        </div>
      </div>

      <el-form ref="paramsForm" :model="dataForm" :rules="rules" label-width="110px" size="small" class="compact-form">
        <el-divider>河流与污染源</el-divider>
        <el-form-item label="选择河流">
          <el-select v-model="selectedRiver" @change="handleRiverChange" placeholder="选择河流">
            <el-option v-for="river in rivers" :key="river.value" :label="river.label" :value="river.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="污染源位置">
          <el-input v-model="pollutionLocation" placeholder="点击右侧图标从地图拾取位置" size="small">
            <el-button slot="append" icon="el-icon-location" @click="pickLocation" circle></el-button>
          </el-input>
        </el-form-item>

        <el-divider>模拟参数</el-divider>
        <el-form-item label="排放量(unit)">
          <el-input v-model="dataForm.emission" placeholder="例如：7200" size="small" style="width:100%" />
        </el-form-item>

        <el-form-item label="排放率(unit/s)">
          <el-input v-model="dataForm.pollution_rate" placeholder="例如：2" size="small" style="width:100%" />
        </el-form-item>

        <el-form-item label="水流速度(m/s)">
          <el-input v-model="dataForm.flow_speed" placeholder="例如：0.5" size="small" style="width:100%" />
        </el-form-item>

        <el-form-item label="步长(min)">
          <el-input v-model="dataForm.timestep" placeholder="例如：5" size="small" style="width:100%" />
        </el-form-item>

        <el-form-item label="总时长(h)">
          <el-input v-model="dataForm.total_time" placeholder="例如：2" size="small" style="width:100%" />
        </el-form-item>

        <el-divider>控制</el-divider>
        <div class="button-row">
          <div class="control-left">
            <el-button type="primary" icon="el-icon-caret-right" @click="startSimulation" :disabled="isAnimating"
              class="btn-start">开始</el-button>
            <el-button :type="isPaused ? 'success' : 'warning'"
              :icon="isPaused ? 'el-icon-caret-right' : 'el-icon-pause'" @click="togglePause" :disabled="!isAnimating"
              class="btn-toggle">{{ isPaused ? '继续' : '暂停' }}</el-button>
          </div>

          <div class="control-right">
            <el-button type="danger" icon="el-icon-refresh" @click="confirmReset">重置</el-button>
          </div>
        </div>

        <!-- <el-divider>状态</el-divider> -->
        <!-- <el-form-item label="当前位置">
          <div class="muted">{{ pollutionLocation || '未选择' }}</div>
        </el-form-item> -->
        <!-- <el-form-item label="进度">
          <el-progress :percentage="(parentProgress !== undefined ? parentProgress : progressPercent)"
            :text-inside="true" ></el-progress>
        </el-form-item> -->
      </el-form>
    <!-- </el-card> -->
  </div>
</template>

<script>
export default {
  name: 'wuranyuankuosanSidebar',
  props: {
    currentTime: {
      type: Number,
      default: 0
    },
    gradientStyle: {
      type: String,
      default: ''
    },
    pollutionLocation: {
      type: String,
      default: ''
    }

    ,
    isAnimating: {
      type: Boolean,
      default: false
    },
    isPaused: {
      type: Boolean,
      default: false
    }
    ,
    parentProgress: {
      type: Number,
      default: undefined
    }

  },
  data() {
    return {
      // 验证规则会放在 data 中以便模板访问
      rules: {
        emission: [
          { required: true, message: '请输入排放量', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || String(value).trim() === '') return callback(new Error('请输入排放量'));
              const n = Number(String(value).trim());
              if (!isFinite(n) || n <= 0) return callback(new Error('排放量应为大于0的数字'));
              callback();
            }, trigger: 'blur'
          }
        ],
        pollution_rate: [
          { required: true, message: '请输入排放率', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || String(value).trim() === '') return callback(new Error('请输入排放率'));
              const n = Number(String(value).trim());
              if (!isFinite(n) || n <= 0) return callback(new Error('排放率应为大于0的数字'));
              callback();
            }, trigger: 'blur'
          }
        ],
        flow_speed: [
          { required: true, message: '请输入水流速度', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || String(value).trim() === '') return callback(new Error('请输入水流速度'));
              const n = Number(String(value).trim());
              if (!isFinite(n) || n <= 0) return callback(new Error('水流速度应为大于0的数字'));
              callback();
            }, trigger: 'blur'
          }
        ],
        timestep: [
          { required: true, message: '请输入步长', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || String(value).trim() === '') return callback(new Error('请输入步长'));
              const n = Number(String(value).trim());
              if (!isFinite(n) || n <= 0) return callback(new Error('步长应为大于0的数字'));
              callback();
            }, trigger: 'blur'
          }
        ],
        total_time: [
          { required: true, message: '请输入总时长', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || String(value).trim() === '') return callback(new Error('请输入总时长'));
              const n = Number(String(value).trim());
              if (!isFinite(n) || n <= 0) return callback(new Error('总时长应为大于0的数字'));
              callback();
            }, trigger: 'blur'
          }
        ]
      },
      dataForm: {
        emission: 7200, // unit
        pollution_rate: 2, // unit/s
        total_time: 2, // h (小时)
        flow_speed: 0.5, // m/s
        timestep: 5, // min (分钟)

      },
      rivers: [
        { value: '巴公河', label: '巴公河' },
        { value: '丹河', label: '丹河' },
        { value: '北马河', label: '北马河' },
        { value: '大东仓河', label: '大东仓河' },
        { value: '小东仓河', label: '小东仓河' },
        { value: '桑家坪河', label: '桑家坪河' },
        { value: '许河', label: '许河' },
        { value: '里河', label: '里河' },
        { value: '野川河', label: '野川河' }
      ],
      selectedRiver: '巴公河'
    };
  },
  computed: {
    // 计算进度百分比：基于 currentTime（s）和 dataForm.total_time（h）
    progressPercent() {
      try {
        const totalSeconds = (this.dataForm && this.dataForm.total_time ? Number(this.dataForm.total_time) : 0) * 3600;
        if (!totalSeconds || !this.currentTime) return 0;
        const p = Math.round((this.currentTime / totalSeconds) * 100);
        return Math.min(100, Math.max(0, p));
      } catch (e) {
        return 0;
      }
    }
  },
  methods: {
        closePanel() {
        this.resetSimulation();
      this.$emit('close');
    },

    handleRiverChange() {
      console.log('选择的河流:', this.selectedRiver);
      this.$emit('river-change', this.selectedRiver);
    },
    // 拾取位置功能
    pickLocation() {
      // 发送事件通知父组件进入位置拾取模式
      this.$emit('pick-location');
    },

    // 开始模拟功能
    startSimulation() {
      // 使用 el-form 的校验规则，校验通过后再触发父组件的 start-simulation
      if (this.$refs.paramsForm) {
        this.$refs.paramsForm.validate((valid) => {
          if (valid) {
            // 将字符串输入转换为 Number 传给父组件，保持类型一致
            const payload = {
              emission: Number(this.dataForm.emission),
              pollution_rate: Number(this.dataForm.pollution_rate),
              total_time: Number(this.dataForm.total_time),
              flow_speed: Number(this.dataForm.flow_speed),
              timestep: Number(this.dataForm.timestep)
            };
            this.$emit('start-simulation', payload);
          } else {
            this.$message && this.$message.error && this.$message.error('参数校验未通过，请检查输入');
          }
        });
      } else {
        // 回退行为：没有表单引用时直接发射
        this.$emit('start-simulation', { ...this.dataForm });
      }
    },
    pauseSimulation() {
      this.$emit('pause-simulation');
    },
    resumeSimulation() {
      this.$emit('resume-simulation');
    },
    resetSimulation() {
      this.$emit('reset-simulation');
    },
    // 切换暂停/继续（在子组件内根据 isPaused prop 决定发射哪个事件）
    togglePause() {
      if (!this.isAnimating) return;
      if (this.isPaused) {
        this.resumeSimulation();
      } else {
        this.pauseSimulation();
      }
    },
    // 带确认的重置
    confirmReset() {
      // 使用 Element UI 的 this.$confirm（如果可用）弹出确认框
      if (this.$confirm) {
        this.$confirm('确定要重置模拟吗？这会清除当前结果。', '重置确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 重置表单验证状态并恢复默认值（可选）
          if (this.$refs.paramsForm && this.$refs.paramsForm.resetFields) {
            this.$refs.paramsForm.resetFields();
          }
          this.resetSimulation();
        }).catch(() => {
          /* 用户取消 */
        });
      } else {
        // fallback
        if (confirm('确定要重置模拟吗？')) {
          if (this.$refs.paramsForm && this.$refs.paramsForm.resetFields) {
            this.$refs.paramsForm.resetFields();
          }
          this.resetSimulation();
        }
      }
    },

  },
  
    beforeDestroy() {
        this.resetSimulation();

    }
};
</script>

<style lang="scss" scoped>
.sidebar {
  width: 350px;
  max-height: calc(100vh - 150px);
  overflow-y: auto;
  z-index: 100;

  // 滚动条样式优化
  &::-webkit-scrollbar {
    width: 5px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
  }
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #307EFF;
  height: 50px;
  border-radius: 0;

  .header-left {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    flex: 1;

    .card-title {
      margin: 0 0 0 10px;
      font-family: Source Han Sans CN;
      font-weight: 500;
      font-size: 18px;
      color: #FFFFFF;
      line-height: 50px;
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    height: 100%;

    .close-btn {
      font-size: 24px;
      color: #fff;
      cursor: pointer;
      transition: color 0.3s;
      margin-right: 10px;

      &:hover {
        color: rgba(255, 255, 255, 0.8);
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 14px;
    font-weight: 600;
  }

  .sub {
    display: block;
    font-size: 11px;
    margin-left: 6px;
  }
}

// 紧凑的表单布局
.el-form {
  margin-bottom: 0;

  &-item {
    margin-bottom: 8px !important;

    &__label {
      font-size: 12px !important;
      padding: 5px 5px 5px 0 !important;
      width: 90px !important;
    }

    &__content {
      margin-left: 90px !important;
      font-size: 12px;
    }
  }
}

// 优化输入框大小
.el-input-number {
  width: 100% !important;

  &__decrease,
  &__increase {
    padding: 0 8px !important;
  }
}

// 位置拾取输入框样式优化
.el-input-group__append .el-button {
  padding: 0 10px;
}

// 按钮行样式
.button-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
  flex-wrap: nowrap;

  .control-left,
  .control-right {
    display: flex;
    gap: 8px;
    align-items: center;
  }
}

// 按钮样式
.btn-start {
  min-width: 110px;
}

.btn-toggle {
  min-width: 80px;
}

// 辅助文本样式
.muted {
  color: #666;
  font-size: 12px;
}

// 确保 divider 文本在一行显示
.compact-form {
  padding: 5px;
  .el-form-item {
    margin-bottom: 8px !important;
  }

  .el-divider .el-divider__text {
    white-space: nowrap;
    padding: 0 8px;
    font-weight: 500;
  }
}
</style>